<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { FormRules, FormInstance } from "element-plus";
import { DataDictionaryApi } from "@/Api";

interface Props {
   modelValue: boolean;
}

const props = withDefaults(defineProps<Props>(), {
   modelValue: false
});

const emit = defineEmits<{
   (e: "update:modelValue", value: boolean): void;
}>();

const loading = reactive({ add: false });
const disable = reactive({ add: false });
const formRef = ref<FormInstance>();
const form = reactive({
   label: "",
   code: ""
});

/** 表单规则 */
const formRules = reactive<FormRules>({
   label: [
      { required: true, message: "显示名称必填", trigger: "blur" },
      {
         min: 2,
         max: 20,
         message: "显示名称在 2 到 20 个字符之间",
         trigger: "change"
      },
      { pattern: /^[\u4E00-\u9FA5]+$/, message: "显示名称必须为中文", trigger: "change" }
   ],
   code: [
      { required: true, message: "内部名称必填", trigger: "blur" },
      {
         min: 3,
         max: 30,
         message: "显示名称在 3 到 30 个字符之间",
         trigger: "change"
      },
      { pattern: /^[A-Za-z_]+$/, message: "内部名称必须由英文字母或下划线组合", trigger: "change" }
   ]
});

const dialogVisible = computed({
   get: () => props.modelValue,
   set: value => {
      if (!value) formRef.value?.resetFields();
      emit("update:modelValue", value);
   }
});

async function handlerAdd() {
   loading.add = true;
   disable.add = true;

   const res = await DataDictionaryApi.Create(form);
   if (res.code == 200) {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
   }

   loading.add = false;
   disable.add = false;
}
</script>

<template>
   <el-dialog v-model="dialogVisible" ref="dialog" title="添加数据字典" width="500" draggable>
      <el-form ref="formRef" :model="form" :rules="formRules">
         <el-form-item label="显示名称:" prop="label">
            <el-input v-model="form.label" placeholder="显示名称(示例: 专业层次)" />
         </el-form-item>
         <el-form-item label="内部名称:" prop="code">
            <el-input v-model="form.code" placeholder="内部名称(示例: level)" />
         </el-form-item>
      </el-form>
      <template #footer>
         <el-button :loading="loading.add" :disabled="disable.add" type="primary" @click="handlerAdd"> 添加 </el-button>
      </template>
   </el-dialog>
</template>

<style lang="scss" scoped>
.el-input {
   width: 100%;
}
</style>
